package leetcode;

public class Lc8 {

    public int myAtoi(String s) {
        s = s.trim();
        if ("".equals(s)) return 0;
        boolean isNegtive = false;
        if (s.charAt(0) == '-') {
            isNegtive = true;
        }
        int idx = 0;
        StringBuilder builder = new StringBuilder();
        if (s.charAt(0) == '-' || s.charAt(0) == '+')    idx++;
        while (idx < s.length() && s.charAt(idx) == '0') idx++;
        while (idx < s.length() && Character.isDigit(s.charAt(idx))) {
            builder.append(s.charAt(idx));
            idx++;
            if (builder.length() > 10) break;
        }
        if (builder.length() == 0)  return 0;
        if (builder.length() >= 10) {
            Long num = Long.valueOf(builder.toString());
            if (isNegtive) {
                if (num * -1 <= Integer.MIN_VALUE)
                    return Integer.MIN_VALUE;
                return Integer.valueOf(builder.toString()) * -1;
            } else {
                if (num > Integer.MAX_VALUE)
                    return Integer.MAX_VALUE;
                return Integer.valueOf(builder.toString());
            }
        }
        int flag = isNegtive ? -1 : 1;
        return Integer.valueOf(builder.toString()) * flag;
    }


    //-2147483648
    // 2147483647
    public static void main(String[] args) {
        System.out.println(1 << 31);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Math.pow(-2,31));
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Math.pow(2, 31));

        System.out.println("  44  ".trim());
    }


}
